package id.net.iconpln.bb.server.controller;

import id.net.iconpln.bb.server.dao.PengendalianDao;
import id.net.iconpln.bb.server.dao.ShipmentDao;
import id.net.iconpln.bb.server.util.SpringApplicationContextUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;

import com.google.gwt.dev.util.collect.HashMap;
/**
 * Servlet implementation class UploadHandler
 */
@Controller
public class UploadHandler extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private String no_rakor = "";   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadHandler() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String jenis = "";
		try{
			jenis = request.getParameter("jenis");
		}catch (Exception e) {
			jenis = "";
		}
		
		try {
			if (jenis.equals("rakor")){
				upload(request, response);
			}else if (jenis.equals("sampling")){
				sampling(request, response);
			}
        }catch (SQLException ex) {
        	ex.printStackTrace();
        }
	}
	
	private void upload(HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException, SQLException{
    	String rootDirectory = getServletContext().getRealPath("upload");
    	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    	File uploadedFile = null;
    	
    	System.out.println("isMultipart " + isMultipart);
    	
    	if (!isMultipart){
    		no_rakor = request.getParameter("no_rakor");
    		request.getSession().setAttribute("no_rakor", no_rakor);
    		System.out.println("no_rakor " + no_rakor);
    	}else if (isMultipart) {
    		DiskFileItemFactory factory = new DiskFileItemFactory();
    		ServletFileUpload upload = new ServletFileUpload(factory);
    		ProgressListener progressListener = new ProgressListener(){
    			   public void update(long pBytesRead, long pContentLength, int pItems) {
    			       if (pContentLength == -1) {
    			       }else{
    			       }
    			   }
    			};
    			upload.setProgressListener(progressListener);
    		try {
    			List items = upload.parseRequest(request);
    			Iterator iter = items.iterator();
    			while (iter.hasNext()) {
    				FileItem item = (FileItem) iter.next();
    				System.out.println("item.isFormField() " + item.isFormField());
    				if (item.isFormField()) {
    				} else {
    					String fileName = item.getName();
    					System.out.println("fileName " + fileName);
    					if (fileName != null && !fileName.equals("")) {
    						fileName = FilenameUtils.getName(fileName);
    						uploadedFile = new File(rootDirectory+"/"+fileName);
    						
    						try {
    							item.write(uploadedFile);
							} catch (Exception e) {
								e.printStackTrace();
							}
    						System.out.println(uploadedFile.getAbsolutePath());
    						
    				    	
    					}
    				}
    			}
    			
    			PengendalianDao pengendalianDao= (PengendalianDao) SpringApplicationContextUtil.getBean("PengendalianDao");
    			
    			Map map = new HashMap();
    			map.put("no_rakor", request.getParameter("no_rakor"));
    			map.put("user", "DHAMARSU");
    			map.put("app_access", "WEB");
    			map.put("crud", "WEB");
    			try{
    				List<Map> lMap = pengendalianDao.insertNotulenRakor("RAKOR_NOTULEN", map, uploadedFile);
    				response.setStatus(200);
    			}catch (Exception e) {
    				response.sendError(400, "Bad Request ........");
    				e.printStackTrace();
				}
    		} catch (FileUploadException e) {
    			e.printStackTrace();
    			response.sendError(400, "Bad Request ........");
    		}
    	}
    }
	
	private void sampling(HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException, SQLException{
    	String rootDirectory = getServletContext().getRealPath("upload");
    	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    	File uploadedFile = null;
    	
    	System.out.println("isMultipart " + isMultipart);    	
    	if (isMultipart) {
    		DiskFileItemFactory factory = new DiskFileItemFactory();
    		ServletFileUpload upload = new ServletFileUpload(factory);
    		ProgressListener progressListener = new ProgressListener(){
    			   public void update(long pBytesRead, long pContentLength, int pItems) {
    			       
    			   }
    			};
    			upload.setProgressListener(progressListener);
    		try {
    			List items = upload.parseRequest(request);
    			Iterator iter = items.iterator();
    			
    			Map mapParam = new HashMap();
    			mapParam.put("no_pengajuan", request.getParameter("no_pengajuan"));	    		
    			mapParam.put("jumlah_sampling", "0");
    			mapParam.put("ts", request.getParameter("ts"));
    			mapParam.put("hgi", request.getParameter("hgi"));
    			mapParam.put("tm", request.getParameter("tm"));
    			mapParam.put("volume", request.getParameter("volume"));
    			mapParam.put("ash", request.getParameter("ash"));
    			mapParam.put("cv", request.getParameter("cv"));
    			mapParam.put("tanggal", request.getParameter("tanggal"));
    			mapParam.put("tgl_pengambilan", request.getParameter("tanggal"));	
    			mapParam.put("user",  request.getParameter("user"));
    			mapParam.put("app_access", "WEB");
    			mapParam.put("status", "KIRIM");
    			mapParam.put("id_surveyor",  request.getParameter("id_surveyor"));
    			mapParam.put("no_sampling",  request.getParameter("no_sampling"));
    			mapParam.put("id_pengiriman", "");
    			mapParam.put("no_sertifikat",  request.getParameter("no_sertifikat"));
    			try{
	    			if (request.getParameter("no_sampling").equals("")){
	    				mapParam.put("crud", "CREATE");
	    			}else{
	    				mapParam.put("crud", "UPDATE");	    			
	    			}
    			}catch (Exception e) {
    				mapParam.put("crud", "CREATE");
				}
    			
    			
    			while (iter.hasNext()) {
    				FileItem item = (FileItem) iter.next();
    				if (item.isFormField()) {    					
    				} else {
    					String fileName = item.getName();
    					System.out.println("fileName " + fileName);
    					if (fileName != null && !fileName.equals("")) {
    						fileName = FilenameUtils.getName(fileName);
    						uploadedFile = new File(rootDirectory+"/"+fileName);    						
    						try {
    							item.write(uploadedFile);
							} catch (Exception e) {
								e.printStackTrace();
							}    						
    					}
    				}
    			}    			
    			System.out.println("uploadedFile " + uploadedFile.getAbsolutePath());
    			mapParam.put("file", uploadedFile.getAbsolutePath());
    			
    			ShipmentDao shipmentDao= (ShipmentDao) SpringApplicationContextUtil.getBean("ShipmentDao");
    			
    			try{
    				List<Map> lMap = shipmentDao.insertPengirimanBB("SAMPLING", mapParam);
    				response.setStatus(200);
    			}catch (Exception e) {
    				response.sendError(400, "Bad Request ........");
    				e.printStackTrace();
				}
    			
    			response.setStatus(200);    			
    		} catch (FileUploadException e) {
    			e.printStackTrace();
    			response.sendError(400, "Bad Request ........");
    		}
    	}
    }
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
		
	}

}
